/**************************************************/
/*      SCC.C                                     */
/*                                                */
/*      2002-01-25 11:05                          */
/*                                                */
/*                                                */
/*      SCC1 - CONTROL                            */
/*      SCC2 - Timing Ant.                        */
/*      SCC3 - DEBUG                              */
/*      SCC4 - Dual operation                     */
/*      SCC5 - TOD                                */
/*      SCC6 - Rb.                                */
/*                                                */
/**************************************************/

#include "../includes.h"



unsigned char control_tx_buf[SCC1_TX_BUF_LENGTH];
unsigned char* control_tx_buf_in;
unsigned char* control_tx_buf_out;

unsigned char monitor_tx_buf[SCC3_TX_BUF_LENGTH];
unsigned char* monitor_tx_buf_in;
unsigned char* monitor_tx_buf_out;

unsigned char tod_tx_buf[TOD_TX_BUF_LENGTH];


unsigned char CommandBuffer1[SCC1_RX_BUF_LENGTH];
unsigned char CommandBuffer2[SCC2_RX_BUF_LENGTH];
unsigned char CommandBuffer3[SCC3_RX_BUF_LENGTH];


//kang char tod_tx_ready = 0;


int scc1_rx_cnt,scc2_rx_cnt,scc3_rx_cnt;

int iGPSRxCnt=0;


char BaudrateString[7][7] = {"2400","4800","9600","19200","38400","57600","115200"};


void Init_SCC(void);
void init_scc1(void);
void init_scc3(void);


void Sub_SCC1(void);
void Sub_SCC3(void);


void Sub_SCC_TX(char);


void SCC13_RECEIVE_HANDLING(char);
void SCC2_RECEIVE_HANDLING();
void SCC13_TRANSMIT_HANDLING(char);

void SendMessageToEB(unsigned char *, unsigned int);
void SendMessageToEB_T(unsigned char *, unsigned int);

void TransmitMessage(unsigned char *,char);
void TransmitnMessage(unsigned char *,int, char);
void OEMV_Print_Func(char c,int fd);
void RbSRO_Func(char c,int fd);

void Init_SCC(void)
{
    scc1_rx_cnt = scc2_rx_cnt = scc3_rx_cnt = 0;

	control_tx_buf_in = control_tx_buf_out = control_tx_buf;
	monitor_tx_buf_in = monitor_tx_buf_out = monitor_tx_buf;
}


//----------------------------------------------------------------------------------
//kang 08-12-01
unsigned char temp_buf[GPSRXBUFSIZE];
unsigned char send_buf[GPSRXBUFSIZE];

GPSBUF_ buf_sync15={0,0,0, 0,0,0, 0,0, };
GPSBUF_ buf_f1000c={0,0,0, 0,0,0, 0,0, };
GPSBUF_ buf_oemv1={0,0,0, 0,0,0, 0,0, };	//sewon
GPSBUF_ buf_RbSRO={0,0,0, 0,0,0, 0,0, };	//sewon
//GPSBUF_ buf_oemv3 ={0,0,0, 0,0,0, 0,0, };   //kay



//char GPS_Rx_TimeOut = 0;
//short GPSRxHead = 0;
//short GPSRxTail = 0;
//unsigned char GPS_Rx_Buf[GPSRXBUFSIZE];
//unsigned char GPS_Rx_Buf_f1000c[GPSRXBUFSIZE];

void SCC2_PUSH(GPSBUF_ *p, char c, int fd)
{

	p->Buf[p->Head] = c;
	p->RxCnt++;

	p->Head = (p->Head + 1) % GPSRXBUFSIZE;

	if( p->Head == p->Tail ){ p->RxCnt =0; }

	p->Rx_TimeOut = 0;


	OEMV_Print_Func(c, fd);//sewon

	RbSRO_Func(c, fd);//sewon

}


void SCC2_RECEIVE_HANDLING_f1000c(GPSBUF_ *p,int fd)
{
	int i,itail;
    int iRlt;
    int len;
    int ii;
    int sat;
	while( p->Buf[p->Tail] != '#' && p->Buf[p->Tail] != '$' && p->Tail != p->Head  ){ //
		p->Tail=(p->Tail+1)%GPSRXBUFSIZE;
		p->RxCnt--;
	}

	if( p->Tail == p->Head || p->RxCnt< 0){
		p->RxCnt = 0 ;
		return ;
	}

	itail = p->Tail;

	len=0;
	iRlt=0;
	for( i=0; i<p->RxCnt && i<GPSRXBUFSIZE ; i++ ){
		temp_buf[i] = p->Buf[ itail ] ;
		len++;
		itail = (itail+1)%GPSRXBUFSIZE;
		if( temp_buf[i] =='\n'){
			//printf(" nmea_msg_rcvd ");

			if( iLsiDebugVariable == 3337 || SYSTEM.IO.CTRL_PORT.MODE == UDEBUG5 ){
				temp_buf[i+1]=0;
				//printf("%d/%d, %d)%s\n",len,p->RxCnt,p->Tail, temp_buf);
				printf("<<<<<<<<<<%s\n",temp_buf);
			}
			temp_buf[i+1]=0;

			if( (CONFIG.iCVType == 0) && (fd == fdEB) && (VME.Data.TimeSync_Mode == VME_CV_MODE) ){		//master mode

				if( (temp_buf[0] == '#') ){	//sewon

					memcpy(send_buf, temp_buf, sizeof(temp_buf));

					if( (CONFIG.NETSEND==1) ){
						net_send(send_buf, strlen(send_buf),0);
						dbgCV(3389)	printf("%s\n",send_buf);
					}
					else if(CONFIG.NETSEND==0){
						VME_CV_write(send_buf, strlen(send_buf));	//VME Master signal	->	slave blockram write
					}
					dbgCV(129) printf("size:%d\ntemp_buf : %s\n",strlen(send_buf),temp_buf);
				}
			}

			oemv3_msg_rcvd( temp_buf, 0, len, SDATA, fd);

//			nmea_msg_rcvd( temp_buf, 0, len);
//			if( iRlt >0 ){
//				if( p->iMatch++ > 1000 ) p->iMatch = 500;
//			}
			iRlt = len ;
			break;
		}
	}


	if( iRlt > 0 ){
		p->Tail = (p->Tail+iRlt)%GPSRXBUFSIZE;
		p->RxCnt = max(0, (p->RxCnt-iRlt) );
		//if( iLsiDebugVariable == 3337 ){ printf("rlt:%4d, %4d(%4d), %3d\n\n",iRlt, p->Tail, p->Head, p->RxCnt); }
	}
}

void SCC2_RECEIVE_HANDLING(GPSBUF_ *p)
{
	int i,itail;
    int iRlt;

    while( p->Buf[p->Tail] != '@' && p->Tail != p->Head  ){ //
		p->Tail=(p->Tail+1)%GPSRXBUFSIZE;
		p->RxCnt--;
	}
	
	if( p->Tail == p->Head || p->RxCnt< 0){
		p->RxCnt = 0 ;
		return ;
	}
	
	itail = p->Tail;
    
	
	for( i=0; i<p->RxCnt && i<GPSRXBUFSIZE ; i++ ){
		temp_buf[i] = p->Buf[ itail ] ;
		itail = (itail+1)%GPSRXBUFSIZE;
	}
    
	iRlt=0;
	iRlt = EBGetCommandID( (BYTE *)temp_buf, i );
	if( iRlt >0 ){
		if( p->iMatch++ > 1000 ) p->iMatch = 500;
	}

	if(monitor.eb){
		sprintf((char*)MESG,"[%3d,%3d,%3d]\n",iGPSRxCnt,TimeSliceCounter,SYSTEM.TIME.TOD_MatchCounter);
		TransmitMessage((BYTE*)MESG,DEBUG_PORT);
    }
	
	if( iRlt > 0 ){
		p->Tail = (p->Tail+iRlt)%GPSRXBUFSIZE;
		p->RxCnt = max(0, (p->RxCnt-iRlt) );
	}

}
//----------------------------------------------------------------------------------

int iQUE_RECEIVE=0;
#define M_QUE_RECEIVE_DEBUG 2
int QUE_RECEIVE_HANDLING(char* buf)
{
int		vRxCount=0;
cmd_msg msg;

	if( IPC.msgQid0 == -1 ){ 
		printf("id -1 "); 
		return 0; 
	}

	//Message Queue handling
	if( msgrcv(IPC.msgQid0, (struct cmd_msg *)&msg, CMD_MSG_SIZE, 0, IPC_NOWAIT) != -1){
		vRxCount = msg.len; 
		//if(iQUE_RECEIVE++%M_QUE_RECEIVE_DEBUG==0)printf("$1:%d\n",iQUE_RECEIVE);
		if(vRxCount>0){
			if(vRxCount>SCC3_RX_BUF_LENGTH){
				vRxCount = SCC3_RX_BUF_LENGTH;
			}
			
			memcpy(buf,msg.data,vRxCount);
		}
		
		return vRxCount;
	}
	else if( lcd_data.head != lcd_data.tail ){
		//if(iQUE_RECEIVE++%M_QUE_RECEIVE_DEBUG==0)printf("$2:%d\n",iQUE_RECEIVE);
		while( lcd_data.head != lcd_data.tail && vRxCount<cmd_msg_buf_size ){
			msg.data[vRxCount++] = lcd_data.buf[ lcd_data.tail++ ];
			if( lcd_data.tail >= lcd_data.size ) lcd_data.tail = 0;
		}
		memcpy(buf,msg.data,vRxCount);
		lcd_data.flag = 1;
		lcd_data.cnt_idle=1;
		//printf("<<%d:in SCC(%d)\n",vRxCount ,lcd_data.tail);
		return vRxCount;
	}
	else{
		//if(iQUE_RECEIVE++%M_QUE_RECEIVE_DEBUG==0)printf("$3:%d\n",iQUE_RECEIVE);
		return 0;
	}
}


void SCC13_RECEIVE_HANDLING(char port)
{
    int 		*RxCount;
    Command_	*Command;

	scc3_rx_cnt = QUE_RECEIVE_HANDLING(CommandBuffer3);
	if(scc3_rx_cnt<=0) {return;}
		
	switch(port){

		case PORT_COMMON:
				Command = &COMMAND.COMMON_PORT;
				RxCount = &scc1_rx_cnt;
				break;
		case PORT_CONTROL:
				Command = &COMMAND.CTRL_PORT;
				RxCount = &scc3_rx_cnt;
				
				//if( 0 && iLsiDebugVariable ==4030 ){
				//	SendMessageToEB(CommandBuffer3,scc3_rx_cnt);
				//	//scc3_rx_cnt=0;
				//}	
				
				break;
	}
	
	if(Command->SERVICE == CMD_PRE_INPUT){
		SetCommand(port);
		Command->SERVICE = CMD_INPUT;
	}
	
    if(Command->SERVICE == CMD_INPUT){

	    switch(Command->COMMAND_SET){

    		case NAVICOM_COMMAND:
							//printf("$$NAVICOM_COMMAND\n");
							NAVICOMCommand(port);
    						break;
	  		case Odetic_COMMAND:
			/*kang
	  						if(odetic_debug) { 
	  							TransmitMessage((BYTE*)"\r\nRX - ",PORT_CONTROL);
	  							TransmitnMessage((BYTE*)CommandBuffer1,*RxCount,PORT_CONTROL);
	  						}
	  		kang*/
							//printf("$$Odetic_COMMAND\n");
							OdeticCommand(port);
			
    						break;
			default:
							break;
    	}
    }

    else {

		*RxCount = 0;
    }
}



/* kang
void SCC13_TRANSMIT_HANDLING(char port)
{
    PORT_		*PORT;


	switch(port){

		case PORT_COMMON:
				PORT = &SYSTEM.IO.COMMON_PORT;

				DisableControlPortTx();
				PORT->Print = OFF;
				//ResetCtrlOccupied();

				break;

		case PORT_CONTROL:
				PORT = &SYSTEM.IO.CTRL_PORT;
				break;
	}

	switch( PORT->MODE ) {
		case	UWAIT_TO_PROMPT:
					TransmitnMessage((BYTE*)PROMPT,PROMPT_LENGTH,port);
					break;
		case	UDISPLAY_LOG:
					//DisplayLog(port);
					break;
		case	UDISPLAY_TLOG:
					DisplayTLog(port);
					break;
		case	UDISPLAY_HELP:
					//kang DisplayHelp(port);
					break;
		case	UWAIT_MEMORY_PRINT:
					break;

	}
}
kang */


unsigned char GPS_Tx_Buf[GPSTXBUFSIZE];
int GPSTxHead = 1;
int GPSTxTail = 0;
int GPS_Tx_Ready = 0;

int tod_tx_head = 1;
int tod_tx_tail = 0;

void SendMessageToEB(unsigned char *Message,unsigned int length)
{
    int i;
//    printf("----SendMessageToEB_____1_____\n");
	for(i=0; i<length; i++)
	{
		if(((GPSTxHead + 1) % GPSTXBUFSIZE) != GPSTxTail) 
       	{
			GPS_Tx_Buf[GPSTxHead] = Message[i];

			GPSTxHead = (GPSTxHead + 1) % GPSTXBUFSIZE;
//			printf("----SendMessageToEB_____2_____\n");
		}
	}

	
	return;
}


//---------------------------------------------------------------------------
//kang 08-12-01
#define MSGOUT_ALL		(1<<0)
#define MSGOUT_EB		(1<<1)
#define MSGOUT_CONTROL	(1<<2)
#define MSGOUT_EBSTR	(1<<3)
#define msgflag_query(flag) (MSGOUT_ALL|flag)


//kang 08-12-01
int SendEBHandler(int fd)
{
    int i;
    int index_temp;
    
	char buf[800+2];
	int ibuf=0;
		
	for(i=0; i<1000;i++){ // dummy limit. 1000 can be modified.
		if( 1 ){
			index_temp = (GPSTxTail+1)%GPSTXBUFSIZE;
			if(index_temp != GPSTxHead)
			{
		        GPSTxTail = index_temp;
	            //buf[i] = GPS_Tx_Buf[GPSTxTail];
		       	//SendOneByte( GPS_Tx_Buf[GPSTxTail] );
				buf[ibuf]=GPS_Tx_Buf[GPSTxTail];
				ibuf++;
		    }
		}
		else break ;
	}
	
	if( msgflag_query(MSGOUT_EB) && ibuf > 0 ){
//		if( CONFIG.RcvType==1 ) write(fd, buf, ibuf);
		if( CONFIG.RcvType==0 ) write(fd, buf, ibuf);
		buf[ibuf]=0;
		//kang printf("ss:%s\n",buf);
	}

    return i;
}


/*
//kang 08-12-01
int SendEBHandler(int fd)
{
    int i;
    int index_temp;

	char buf[800+2];
	int ibuf=0;

	for(i=0; i<1000;i++){ // dummy limit. 1000 can be modified.
		if( 1 ){
			index_temp = (GPSTxTail+1)%GPSTXBUFSIZE;
			if(index_temp != GPSTxHead)
			{
		        GPSTxTail = index_temp;
	            //buf[i] = GPS_Tx_Buf[GPSTxTail];
		       	//SendOneByte( GPS_Tx_Buf[GPSTxTail] );
				buf[ibuf]=GPS_Tx_Buf[GPSTxTail];
				ibuf++;
		    }
		}
		else break ;
	}

	if( msgflag_query(MSGOUT_EB) && ibuf > 0 ){
//		if( CONFIG.RcvType==1 ) write(fd, buf, ibuf);
		if( CONFIG.RcvType==0 ) write(fd, buf, ibuf);
		buf[ibuf]=0;
		//kang printf("ss:%s\n",buf);
	}
	
    return i;
}
*/
//---------------------------------------------------------------------------
//kang 08-12-01
char buf_temp[2000];
//char buf_temp[3840];	//sewon

int ReceiveEBHandler(int fd)
{
   	struct  timeval time_out;
 	fd_set readfs;       // file descriptor set 
	
    int index_temp;
	
	int iRead=0;
	int i=0;
	
	//#define NO_DATA_TIMEOUT 20000       // 50 miilisecond
	#define NO_DATA_TIMEOUT 40000         // 100 miilisecond
   	time_out.tv_usec = NO_DATA_TIMEOUT;   // milliseconds 
   	time_out.tv_sec  = 0;                 // seconds 

	//FD_ZERO(&readfs);
	//FD_SET(fd, &readfs);
	
	//tcflush(fd, TCIFLUSH);
	
	//select(fd+1, &readfs, NULL, NULL, &time_out);
	
	//if(FD_ISSET(fd,&readfs)){
	iRead = read(fd,buf_temp,2000);
//	iRead = read(fd,buf_temp,3840);	//sewon 12-05-25
  	//}
	if(iRead<=0) return 0;


	for( i=0; iRead>0 && i< iRead ;i++ )
	{
		if( CONFIG.RcvType==1 )
		{
			SCC2_PUSH(&buf_sync15, buf_temp[i], fd);
		}
		else{
			if( fd == fdEB )				SCC2_PUSH(&buf_f1000c, buf_temp[i], fd);
			else if( fd == fdEB2 )		SCC2_PUSH(&buf_oemv1, buf_temp[i], fd);
			else if( fd == fdRbSRO )	SCC2_PUSH(&buf_RbSRO, buf_temp[i], fd);
		}
	}
//	dbgCV(132) printf("===============\n%s==============\n",buf_f1000c);

	if( iRead>0 ){

		if( iLsiDebugVariable == 3335 )
			printf("Check:%d) %d,%d"
					", %d:%c,%c,%c,%c,\n"
					,CONFIG.RcvType, fd,iRead
					, (int)buf_temp[0], (int)buf_temp[0], (int)buf_temp[1], (int)buf_temp[2], (int)buf_temp[3]);
		buf_temp[iRead]=0;
		if( iLsiDebugVariable == 3336 ) printf("%s\n", buf_temp);
	}
	
    return iRead;
}
//---------------------------------------------------------------------------

// kang 08-12-01
void MonitorGPSinput(GPSBUF_ *p,int fd)
{
    if(p->Tail != p->Head)
    {
    	//if( p == &buf_sync15)  SCC2_RECEIVE_HANDLING(p);
    	if( CONFIG.RcvType==1 )
    		{
    		SCC2_RECEIVE_HANDLING(p);
    		}
 	    else SCC2_RECEIVE_HANDLING_f1000c(p,fd);
    	return;
    }
}


void TransmitMessage(unsigned char *string,char Port)
{
	int i,length;

	//length = strlen((char*)string);

	if (Port == PORT_COMMON ) {
	
	}
		
	if (Port == PORT_CONTROL ) {
		printf((char*)string);
		udp_local_cmd_send((char*)string);
	}
	
	return ;
	
	if (Port == PORT_COMMON ) {
		for(i = 0; i < length; i++) {
			
			if(odetic_debug){*(monitor_tx_buf_in++) = *(control_tx_buf_in++) = *(string++);}
			else{*(control_tx_buf_in++) = *(string++);}
				
			if(control_tx_buf_in > &control_tx_buf[SCC1_TX_BUF_LENGTH-1]){
				control_tx_buf_in = control_tx_buf;
			}
				
			if(odetic_debug)
			{
				if(monitor_tx_buf_in > &monitor_tx_buf[SCC3_TX_BUF_LENGTH-1]){
					monitor_tx_buf_in = monitor_tx_buf;
				}
			}
		}
	}

	if (Port == PORT_CONTROL ) {
		for(i = 0; i < length; i++) {
			*(monitor_tx_buf_in++) = *(string++);
			if(monitor_tx_buf_in > &monitor_tx_buf[SCC3_TX_BUF_LENGTH-1]){
				monitor_tx_buf_in = monitor_tx_buf;
			}
		}
	}
}



void TransmitnMessage(unsigned char *string,int length, char Port)
{
	int i;

	if (Port == PORT_COMMON ) {
		for(i = 0; i < length; i++) {
			
			if(odetic_debug){*(monitor_tx_buf_in++) = *(control_tx_buf_in++) = *(string++);}
			else{*(control_tx_buf_in++) = *(string++);}
				
			if(control_tx_buf_in > &control_tx_buf[SCC1_TX_BUF_LENGTH-1]){
				control_tx_buf_in = control_tx_buf;
			}
			
			if(odetic_debug)
			{
				if(monitor_tx_buf_in > &monitor_tx_buf[SCC3_TX_BUF_LENGTH-1]){
					monitor_tx_buf_in = monitor_tx_buf;
				}
			}
		}
	}

	if (Port == PORT_CONTROL ) {
		for(i = 0; i < length; i++) {
			*(monitor_tx_buf_in++) = *(string++);
			if(monitor_tx_buf_in > &monitor_tx_buf[SCC3_TX_BUF_LENGTH-1]){
				monitor_tx_buf_in = monitor_tx_buf;
			}
		}
	}

	if( Port == PORT_TOD){

		//kang if(tod_tx_ready!=0)return;
		
		for(i=0; i<length; i++)
		{
			if(((tod_tx_head + 1) % TOD_TX_BUF_LENGTH) != tod_tx_tail) 
	       	{
				tod_tx_buf[tod_tx_head] = string[i];
				tod_tx_head = (tod_tx_head + 1) % TOD_TX_BUF_LENGTH;
			}
		}
		if(length > 0) 
		{
			//kang tod_tx_ready = 1;
			//EnGPSTx();
		}

	}
}




//==================================================
// IS-2000 : 68302� SCC3-Control Port �.
//==================================================
void ChangeBaudRate(char port, char baudrate)
{

}



void OEMV_Print_Func(char c,int fd)
{
	if( SYSTEM.EB.print_Flag == ON && fd == fdEB ) { printf("%c",c); }	//OEMV2 print
	if( SYSTEM.EB.print_Flag == OFF && fd == fdEB ){
		if( (c == '<' || c == '[') ){
			SYSTEM.EB.command_Flag = ON;
			printf("\n");
		}
		if( SYSTEM.EB.command_Flag == ON ){
			if( c == 0x0A || c == ']')	{SYSTEM.EB.command_Flag = OFF;}
			printf("%c",c);
		}
	}
	if( SYSTEM.EB2.print_Flag == ON && fd == fdEB2 ) { printf("%c",c); }	//OEMV1 print
	if( SYSTEM.EB2.print_Flag == OFF && fd == fdEB2 )
	{
		if( (c == '<' || c == '[') ){
			SYSTEM.EB2.command_Flag = ON;
			printf("\n");
		}
		if( SYSTEM.EB2.command_Flag == ON ){
			if( c == 0x0A || c == ']')	{SYSTEM.EB2.command_Flag = OFF;}
			printf("%c",c);
		}
	}
}

void RbSRO_Func(char c,int fd)
{
	if( rb.sro100.print_Flag == 1 && fd == fdRbSRO ) printf("%c",c);
}
